package com.sql.test;

import com.mysql.cj.x.protobuf.MysqlxPrepare;
import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class jdbc03 {
    public static void main(String[] args) {

    }

    @Test
    public void connext01() throws IOException, ClassNotFoundException, SQLException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

//        1.注册驱动
        Class.forName(driver);
//        2.得到链接
        Connection connection = DriverManager.getConnection(url, user, password);
//        3.得到statement   存在SQL注入风险
        Statement statement = connection.createStatement();

//        3.1.PreparedStatement防止sql注入
        String sql2 = "select id,name,pwd,sex from ztm.student where name = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql2);
        preparedStatement.setString(1,"小明");
/*//      4.组织sql
        String sql = "INSERT INTO ztm2025.user02 VALUES(2)";
//        5.1插入数据
        int rows = statement.executeUpdate(sql);
        System.out.println(rows > 0 ? "成功" : "失败");*/

//        5.2查询数据
        String sql = "select id,name,pwd,sex from ztm.student";
        ResultSet resultSet = statement.executeQuery(sql);

//        5.3循环取数
        while (resultSet.next()) {
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            String pwd = resultSet.getString(3);
            String sex = resultSet.getString(4);

            System.out.println(id + "\t"+name + "\t"+pwd + "\t"+sex);
        }



//        6.关闭连接
        resultSet.close();
        statement.close();
        connection.close();
    }
}
